package com.koron.car.web.carledger.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.OrderItem;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.car.web.carledger.bean.entity.Car;
import com.koron.car.web.carledger.bean.query.CarQuery;
import com.koron.car.web.carledger.bean.vo.CarVO;
import com.koron.car.web.carledger.service.CarService;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.business.common.entity.EqCodeBean;
import com.koron.common.core.business.common.mapper.EqCodeBeanMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.interceptor.OrderByInterceptor;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.FilesUtil;
import com.koron.common.core.util.dfs.FastDFSClientWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/car")
@Api(tags = "车辆管理-车辆台账")
public class CarController {

    @Autowired
    private CarService carService;

    @GetMapping("/selectOne")
    @ApiOperation("根据车辆id查询车辆信息")
    @ApiImplicitParam(name = "carId", value = "车辆id", required = true)
    public Response<CarVO> selectOne(String carId) {
        log.info("根据车辆id查询车辆信息， carId = {}", carId);
        CarVO bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carService, "queryById", CarVO.class, carId);
        Assert.isTrue(!Objects.isNull(bean) && !bean.getDeleteFlag(), "车辆信息不存在");
        return Response.ok(bean);
    }

    @GetMapping("/queryList")
    @ApiOperation("根据条件查询车辆列表")
    public Response<PageInfo<CarVO>> queryList(CarQuery query) {
        log.info("根据条件查询车辆列表， query = {}", JSON.toJSONString(query));
        List<OrderItem> list = new ArrayList<>();
        for (OrderItem order : query.getOrders()) {
            log.info(order.getColumn());
            if (!order.getColumn().equals("`owner_org_name`")) {
                list.add(order);
            }
        }
        OrderByInterceptor.setOrderBy(list);
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<CarVO> beans = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carService, "queryList", List.class, query);
        return Response.ok(new PageInfo<>(beans));
    }

    @GetMapping("/schedulable")
    @ApiOperation("可调度的车辆查询")
    public Response<List<CarVO>> schedulable(CarQuery query) {
        log.info("可调度的车辆查询， query = {}", JSON.toJSONString(query));
        List<CarVO> beans = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carService, "schedulable", List.class, query);
        return Response.ok(beans);
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation("保存和更新车辆信息")
    public Response<Car> saveOrUpdate(@RequestBody CarVO car) {
        log.info("保存和更新车辆信息， car = {}", JSON.toJSONString(car));
        // 防止通过保存接口删除数据
        car.setDeleteFlag(false);
        CarVO bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carService, "saveOrUpdate", CarVO.class, car);
        return Response.ok(bean);
    }

    @GetMapping("/deleteById")
    @ApiOperation("根据车辆id逻辑删除车辆信息")
    @ApiImplicitParam(name = "carId", value = "carId", required = true)
    public Response<String> deleteById(@CasUser @ApiIgnore EamUser user, @RequestParam String carId) {
        ADOConnection.runTask(user.getCurrDs(), carService, "hiddenById", Boolean.class, carId);
        return Response.ok("删除成功", carId);
    }

    @GetMapping("/getBoundCar")
    @ApiOperation("根据状态获取所有绑定的车辆")
    public Response<List<Car>> getBoundCar(CarQuery query) {
        log.info("根据状态获取所有绑定的车辆");
        List<Car> cars = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carService, "getBoundCar", List.class, query);
        return Response.ok(cars);
    }

    @GetMapping("/updateState")
    @ApiOperation("更新车辆状态")
    public Response<Car> updateState(CarVO car) {
        log.info("更新车辆状态, info = {}", JSON.toJSONString(car));
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), carService, "updateState", Boolean.class, car.getId(), car.getState());
        return Response.ok(car);
    }

    /**
     * 提供给common服务,对未进行冗余的车辆二维码，进行冗余
     * @param carId         车辆id
     * @param licPlateNum   车牌号
     * @return
     */
    @ApiOperation("冗余的车辆二维码")
    @GetMapping(value = "/redundancyERcode")
    public Response<EqCodeBean> redundancyERcode(String carId, String licPlateNum, String envVersion) {
        // 生成二维码
        File file = carService.createMiniProgramQRCode(carId, licPlateNum, envVersion);
        Car carbean = new Car();
        carbean.setId(carId);
        carbean.setLicPlateNum(licPlateNum);
        // 上传二维码
        EqCodeBean eqCodeBean = uploadERcodeImg(carbean, file, envVersion);
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), factory -> {
            factory.getMapper(EqCodeBeanMapper.class).insertSelective(eqCodeBean);
            return true;
        }, Boolean.class);
        return Response.ok(eqCodeBean);
    }

    /**
     * fdfs客户端
     */
    @Autowired
    private FastDFSClientWrapper fdfsCient;

    /**
     * 上传台账二维码img
     * @param bean
     * @param file
     * @return
     */
    private EqCodeBean uploadERcodeImg(Car bean, File file, String envVersion) {
        FilesUtil filesUtil = new FilesUtil();
        MultipartFile multipartFile = filesUtil.fileToMultipartFile(file);
        log.debug("图片大小：" + multipartFile.getSize());
        String path = "";
        try {
            path = fdfsCient.uploadFile(multipartFile);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        EqCodeBean eqcode = new EqCodeBean();
        eqcode.setId(CodeTools.getCode32());
        eqcode.setEquipmentId(bean.getId());
        eqcode.setEquipmentName(bean.getLicPlateNum());
        eqcode.setEnvVersion(envVersion);//环境develop，release，trial
        eqcode.setEqType("car");
        eqcode.setGroupName(StrUtil.split(path, "/").get(0));
        eqcode.setPath(path);
        eqcode.setFileSize(multipartFile.getSize());
        eqcode.setExtension("jpg");
        eqcode.setCreateTime(new Date());
        eqcode.setCreateByName(DateUtil.format(new Date(), DateTimeFormatter.ISO_LOCAL_DATE));
        return eqcode;
    }
}
